/*
 * RingBuffer.h
 *
 *  Created on: Jun 28, 2024
 *      Author: root
 */

#ifndef BSP_RINGBUFFER_H_
#define BSP_RINGBUFFER_H_
#include "basic_header.h"

namespace bsp {

class RingBuffer {
private:
	uint32_t write_pos;
	uint32_t read_pos;
	uint32_t overwrite_count;

	std::vector<char> buffer;

	auto getReadPos() {
		return read_pos;
	}
	auto getWritePos() {
		return write_pos;
	}

public:
	RingBuffer(int max_buf_size = 1024) :
			write_pos { 0 }, read_pos { 0 }, overwrite_count { 0 } {
		ASSERT(max_buf_size > 0, "buffer_size must > 0");
		buffer = std::vector<char>(max_buf_size);
	}

	~RingBuffer() = default;

	void append(const char *data, uint32_t len);
	void append(std::string &str) {
		return append(str.c_str(), str.size());
	}

	uint32_t retrieve(char *data, uint32_t size);
	std::string retrieve(uint32_t size);
	std::string retrieve() {
		return retrieve(buffer.size());
	}

	uint32_t getReadableSize(uint32_t *size1 = nullptr, uint32_t *size2 =
			nullptr);

	uint32_t getWritableSize() {
		return read_pos > write_pos ?
				read_pos - write_pos - 1 :
				buffer.size() - (write_pos - read_pos) - 1;
	}

	uint32_t getOverwriteCount() {
		return overwrite_count;
	}

	int readFd(int fd);
	int writeFd(int fd);

	static void test1();
	static void test2();
};

} /* namespace bsp */

#endif /* BSP_RINGBUFFER_H_ */
